<template>
  <div class="register-form">
     <div class="title-box">
        <h1>注册</h1>
      </div>
    <el-form :model="registerform" :rules="rules" ref="registerFormRef">
      <!-- 注册的第一个界面 -->
      <div v-if="step === 1">
        <el-form-item  prop="username">
          <el-input v-model="registerform.username" type="text" placeholder="昵称" clearable></el-input>
        </el-form-item>
        <el-form-item prop="account">
          <el-input v-model="registerform.account" type="text" placeholder="用户名" clearable></el-input>
        </el-form-item>
        <el-form-item  prop="password">
          <el-input v-model="registerform.password" type="password" placeholder="密码" clearable show-password></el-input>
        </el-form-item>
        <el-form-item  prop="confirmPassword">
          <el-input v-model="registerform.confirmPassword" type="password" placeholder="确认密码" clearable show-password></el-input>
        </el-form-item>
      </div>
      <!-- 注册的第二个界面 -->
      <div v-if="step === 2">
        <el-form-item  prop="email">
          <div class="email-box">
            <el-input style="width:68%" v-model="registerform.email" type="email" placeholder="邮箱" clearable></el-input>
            <el-button style="width:27%" @click="sendVerificationCode">发送验证码</el-button>
          </div>
        </el-form-item>
        <el-form-item  prop="IdentifyingCode">
          <el-input style="width:90%" v-model="registerform.IdentifyingCode" type="text" placeholder="验证码" clearable></el-input>
        </el-form-item>
      </div>
      <div class="button-box" v-if="step === 1">
        <el-button @click="goToStep2">下一步</el-button>
        <p @click="switchToLogin">已有账号? 去登录</p>
      </div>
      <div class="button-box" v-if="step === 2">
        <el-button @click="completeRegistration">完成注册</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup>
    import { ref, reactive,getCurrentInstance  } from 'vue';
    import { useRouter } from 'vue-router';
    import { ElMessage } from 'element-plus';
    import axios from 'axios';

    const router = useRouter();
    const step = ref(1);
    const registerFormRef = ref();
    const { proxy } = getCurrentInstance();

    const registerform = reactive({
        username: '',
        account: '',
        password: '',
        confirmPassword: '',
        email: '',
        IdentifyingCode: ''
    });

    const rules = {
        username: [
            { required: true, message: '请输入昵称', trigger: 'blur' },
            { min: 3, max: 10, message: '昵称长度必须在 3 到 10 个字符之间', trigger:  ['blur','change'] }
        ],
        account: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 6, max: 16, message: '用户名长度必须在 6 到 16 个字符之间', trigger:  ['blur','change'] }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 16, message: '密码长度必须在 6 到 16 个字符之间', trigger:  ['blur','change'] },
            { pattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/, message: '密码必须包含字母和数字', trigger:  ['blur','change'] },
        ],
        confirmPassword: [
            { required: true, message: '请再次输入密码', trigger: 'blur' },
            { validator: (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== registerform.password) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            }, trigger: ['blur','change'] }
        ],
        email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱格式', trigger: ['blur', 'change'] }
        ],
        IdentifyingCode: [
            { required:true,min: 1, message: '请输入验证码', trigger: 'blur' }
        ]
    };

    const validateStep1Fields = () => {
        return new Promise((resolve, reject) => {
        registerFormRef.value.validateField('username', (usernameValid) => {
            if (!usernameValid) {
                    reject('username');
            }
            registerFormRef.value.validateField('account', (accountValid) => {
                if (!accountValid) {
                     reject('account');
                }
                registerFormRef.value.validateField('password', (passwordValid) => {
                if (!passwordValid) {
                     reject('password');
                }
                registerFormRef.value.validateField('confirmPassword', (confirmPasswordValid) => {
                    if (!confirmPasswordValid) {
                    reject('confirmPassword');
                    }
                    resolve();
                });
                });
            });
            });
        });
    };
    //跳转到下一步
    const goToStep2 = async() => {
        try {
            await validateStep1Fields();
            step.value = 2;
        } catch (error) {
            ElMessage.error('请修正表单错误后再继续');
        }
    };
    //发送验证码
    const sendVerificationCode = async () => {
        await registerFormRef.value.validateField('email', async (emailValid) => {
            if (emailValid) {
                try {
                     await proxy.$http.post('/RegisterForm/', {
                            type:'sendVerificationCode',
                            'user_name': registerform.account,
                            'nickname': registerform.username,
                            'pass_word': registerform.password,
                            'pass_ensure': registerform.confirmPassword,  // 修正拼写错误
                            'email': registerform.email
                        }
                    ).then((res)=>{
                        if(res.data.status=="success"){
                            ElMessage.success('验证码已发送到您的邮箱');
                        }else{
                            ElMessage.error(res.data.message);
                        }
                    });
                } catch (error) {
                    ElMessage.error('发送验证码请求失败');
                }
            } else {
                ElMessage.error('请修正邮箱错误后再尝试发送验证码');
            }
        });
    };

    const completeRegistration = async () => {
            await registerFormRef.value.validateField('IdentifyingCode', async(valid) => {
                if(valid){
                    await proxy.$http.post('/RegisterForm/', {
                            type:'register',
                            user_name:registerform.account,
                            code:registerform.IdentifyingCode
                    }).then((res)=>{
                            if(res.data.status=="success"){
                                router.push('/user/login');
                                ElMessage.success('注册成功');
                            }else{
                                ElMessage.error(res.data.message);
                            }
                    }).catch((err)=>{
                        ElMessage.error('请求失败，请稍后重试');
                    });
                }else{
                    ElMessage.error('请输入验证码')
                }
            });
    };

    const switchToLogin = () => {
        router.push('/user/login');
    };
    //返回到上一步
    const goBack = () => {
        step.value = 1; // Move back to step 1
    };
</script>

<style scoped>
    .register-form {
        height: 100%;
        width: 50%;
        position: absolute;
        top: 0;
        left: 0;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .title-box {
        margin-top: 25%;
        margin-bottom: 10%;
    }
    .title-box h1{
        text-align: center;
        align-items: center;
        letter-spacing: 5px;
        color: white;
        text-shadow:4px 4px 3px rgba(0,0,0,.1);
        font-size: 25px;
    }
    .el-form{
        width: 60%;
    }
    .button-box{
        display: flex;
        justify-content: center;
        align-items: center; 
    }
    .el-input{   
        height: 100%;
        text-indent: 4px;
        border: 1px solid #b0cfe9;
    }
    button{
        width:100px;
        height: 30px;
        line-height: 30px;
        border: none;
        border-radius: 4px;
        background-color: #69b3f0;
        color: white;
        margin-right: 5px;
    }
    .button-box p{
        color: white;
    }
    .button-box p:hover{
        cursor: pointer;
    }
    .email-box{
        width: 100%;
        display: flex;
        align-items: center;
        gap: 10px;
    }
   
</style>